package com.china.api.wechat.processor.main;

import java.io.IOException;

import redis.clients.util.SafeEncoder;

import com.china.api.wechat.FrontendConfig;
import com.china.itapi.common.redis.*;
import com.china.itapi.common.util.SerializeUtil;
/**
 * 
 * @Description:
 * @author:zhaoxudong
 * @version:v1.0.0
 * @Created:2013年12月21日上午11:31:19
 * @Modified:
 */
public class SessionManager {

	private static final String SESSION_KEY = "session_";
	private static CacheClient client = CacheManager.commonCache;

	public static Session getSession(String userId) throws IOException {
		Session session = null;
		String data = client.get(SESSION_KEY + userId);
		if (data != null) {
			session = SerializeUtil.deSerializeJson(data, Session.class);
		} else {
			session = new Session(userId);
			saveSession(session);
		}
		return session;
	}

	public static void saveSession(Session session) {
		client.setex(SESSION_KEY + session.getUserId(), FrontendConfig.getSessionTimeOut(), SerializeUtil.serializeJson(session));
	}

	public static void removeSession(Session session) {
		session.clear();
		client.expire(SafeEncoder.encode(SESSION_KEY + session.getUserId()), 0);
	}
}
